package com.zr.controller;


import com.zr.dto.MenuDTO;
import com.zr.dto.StaffFileDTO;
import com.zr.interfaces.IStaffService;
import com.zr.pojo.Result;
import com.zr.utils.POIUtils;
import com.zr.vo.StaffVO;
import com.zr.vo.StaffFileVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author: peterChen
 * @date: 2019/11/14 20:46
 * @description: com.zr.controller
 * @version: 1.0
 */
@Slf4j
@RestController
//@RequestMapping("api")
public class StaffController {
    @Autowired
    private IStaffService staffService;


    /**
     * 单个添加员工信息
     *
     * @param staffVO
     * @return
     */
    @RequestMapping("addStaff")
    @PreAuthorize("hasAuthority('admin')")
    public Result addStaff(@RequestBody StaffVO staffVO) {
        if (staffVO == null) {
            return Result.serviceFail("serviceFail");
        }
        staffService.addStaff(staffVO);
        return Result.success("添加成功");
    }

    /**
     * excel员工批量导入
     * @param excelFile
     * @return
     */
    @RequestMapping("upload")
    @PreAuthorize("hasAuthority('admin')")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            //判断文件是否为空，是否为excel文件
            POIUtils.checkFile(excelFile);
            //读取Excel文件数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            if(list != null && list.size()> 0) {
                staffService.add(list);
            }else{
                return Result.serviceFail("请先填写需上传员工信息");
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件异常：{}",e.getMessage());
            return Result.serviceFail("新增文件类型异常");
        }
        return Result.success("批量新增成功");
    }

    /**
     * 获取菜单  未完成
     *
     * @param roleId
     * @return
     */
    @RequestMapping("getAllMenus")
    @PreAuthorize("isAuthenticated()")
    public Result getMenus(@RequestParam(name = "roleId", required = false) Integer roleId) {
        List<MenuDTO> menuDTOS = staffService.getAllMenus(roleId);
        if (CollectionUtils.isEmpty(menuDTOS)) {
            return Result.serviceFail("获取菜单失败，请重新加载");
        }
        return Result.success("获取菜单成功");
    }

    /**
     * 多文件上传
     * @param files
     * @return
     */
    @RequestMapping("uploadFiles")
    @PreAuthorize("hasAuthority('admin')")
    public Result uploadFiles(@RequestParam("file")MultipartFile[] files){
        List<StaffFileDTO> fileList = staffService.uploadFiles(files);
        log.info("上传附件返回的文件信息：" + fileList);
        return Result.success(fileList);
    }



    /**
     * 批量导入的模板下载
     * @param response
     * @return
     */
    @RequestMapping("download")   //此处尽量get请求
    @PreAuthorize("isAuthenticated()")
    public Result downLoadTemplate(HttpServletResponse response){

        try {
            // 获取资源中的模板文件
            ClassPathResource resource = new ClassPathResource("/templates/staff.xls");
            InputStream inputStream = resource.getInputStream();
            // 根据不同excel创建不同对象,Excel2003版本-->HSSFWorkbook,Excel2007版本-->XSSFWorkbook
            Workbook wb = WorkbookFactory.create(inputStream);
            response.reset();
            response.setContentType("multipart/form-data");
            // 判断excel文件类型，下载获取到的模板并重新命名
           log.info("excel文件类型：" + wb.getClass().getSimpleName());
            if (wb.getClass().getSimpleName().equals("HSSFWorkbook")) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String("staff".getBytes("UTF-8"), "iso8859-1") + ".xls");
            } else {
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String("staff".getBytes("UTF-8"), "iso8859-1") + ".xlsx");
            }
            wb.write(response.getOutputStream());
        }catch (Exception E){
            log.error("下载异常：{}",E.getMessage());
            return Result.serviceFail("下载模板异常");
        }
        return null;
    }
}
